<template>
  <div class="blogEdit_box">
    <!--添加or修改区域-->
    <el-dialog
        :title="titleTemp"
        :before-close="closeModel"
        :visible.sync="centerDialogVisible"
        fullscreen
        center
    >
      <el-form :model="article" style="margin-top: 10px">
        <el-row>
          <el-col :span="5">
            <el-form-item label="文章标题" :label-width="formLabelWidth">
              <el-input v-model="titleTemp" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item :label-width="formLabelWidth" label="所属类别">
              <el-select v-model="categoryTemp" filterable placeholder="请选择所属类别">
                <el-option
                    v-for="item in category"
                    :key="item.id"
                    :label="`${item.category} - ${tempSecret[item?.isSecret]}`"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item :label-width="formLabelWidth" label="所属标签">
              <el-select
                  v-model="labelTemp"
                  multiple
                  collapse-tags
                  style="margin-left: 20px;"
                  placeholder="请选择">
                <el-option
                    v-for="item in label"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label">
                  <span>{{item.label}} - {{tempSecret[item?.isSecret]}}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item :label-width="formLabelWidth" label="是否私密">
              <el-select v-model="secretTemp" filterable placeholder="请选择是否私密">
                <el-option
                    v-for="item in secret"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="标题图" :label-width="formLabelWidth">
              <el-col :span="2">
                <el-upload
                    style="width: 80px"
                    :show-file-list="false"
                    ref="upload"
                    action="#"
                    :on-change="handleChangeUpload"
                    :auto-upload="false"
                    multiple>
                  <img v-if="avatar" :src="avatar" class="imgAvatar" alt="">
                  <i v-else class="el-icon-plus avatar-img-icon"></i>
                </el-upload>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :spam="24">
            <el-form-item :label-width="formLabelWidth" label="内容">
              <mavon-editor placeholder="输入文章内容..."  style="height: 500px" ref=md
                  v-model="contentMd" @imgDel="imgDel" @change="" @imgAdd="imgAdd"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="closeModel">取 消</el-button>
            <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {secret} from "@/utils/enum";

export default {
  data() {
    return {
      tempSecret: secret,
      formLabelWidth: "120px",
      titleTemp: "",
      secret: [{
        value: 'PUBLIC',
        label: '公开'
      }, {
        value: 'PRIVATE',
        label: '私密'
      }],
      secretTemp: "",
      avatar: "",
      label: [],
      labelTemp: "",
      category: [],
      categoryTemp: null,
      title: "",
      categoryName: "",
      centerDialogVisible: true,
      article: {},
      aid: 0,
      contentMd: ""
    }
  },
  methods: {
    handleChangeUpload(file) {
      let that = this
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e){
        that.avatar = this.result;
      }
    },
    submit: function () {
      let that = this
      this.article.content = this.$refs.md.d_render
      this.article.title = this.titleTemp
      this.article.secret = this.secretTemp
      this.article.avatar = this.avatar
      this.article.cid = this.categoryTemp
      this.article.contentMd = this.contentMd
      this.article.labelNames = this.labelTemp.join(", ")
      that.$http.post('/admin/blog/save', this.article).then(res => {
        that.$message({
          message: '文章已成功添加/编辑！',
          type: 'success'
        });
        that.$router.push('/blog/index')
      });
    },
    closeModel:function (done){
      let that = this
      if(this.article.title != null && this.article.title !== "") {
        this.$confirm("是否关闭博客编辑窗口", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          that.$router.push('/blog/index')
        }).catch(() => {
          this.$message.info("已取消")
        });
      } else {
        that.$router.push('/blog/index')
      }
    },
    imgAdd: function (pos, $file) {
      // pos为位置，$file为图片文件
      let formdata = new FormData();
      formdata.append("image", $file);
      // 按照格式传入对于的图片文件
      this.$http.post('/img/blog/upload', formdata).then((res) => {
        // 请求后端接口后，将pos位置的图片路径替换为后端返回的图片链接
        this.$refs.md.$img2Url(pos, res.data);
      });
    },
    imgDel: function (filename) {
      let temp = filename[0].split("/")
      this.$http.post('/img/blog/delete/' + temp[temp.length - 1]).then((res) => {
        console.log("删除成功！")
      });
    },
    async getCategory() {
      const {data: res} = await this.$http.get('/admin/category/list', {
        params: {
          page: 1,
          size: 9999
        }
      }, {
        emulateJSON: true
      })
      // 类别列表赋值
      this.category = res.content
    },
    async getLabel() {
      const {data: res} = await this.$http.get('/admin/label/list', {
        params: {
          page: 1,
          size: 9999
        }
      }, {
        emulateJSON: true
      })
      // 类别列表赋值
      this.label = res.content
    },
    async getArticle(id) {
      const {data: res} = await this.$http.get('/blog/info', {
        params: {
          id: id
        }
      }, {
        emulateJSON: true
      })
      // 类别列表赋值
      this.article = res
      this.secretTemp = res.isSecret
      this.titleTemp = res.title
      this.avatar = res.avatar
      this.categoryTemp = res.cid.id
      this.labelTemp = res.labelNames.split(", ")
      this.contentMd = res.contentMd
    }
  },
  created() {
    // 获取类别
    this.getCategory()
    // 获取标签
    this.getLabel()
    this.aid = this.$route.params.id
    if (this.aid === "0") {
      this.article = {}
    } else {
      this.getArticle(this.aid)
    }
  }
}
</script>


<style>
.avatar-img-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: 110px;
  text-align: center;
}

.imgAvatar {
  width: 200px;
  height: 110px;
  display: block;
}

.uploadImgBody :hover {
  border: dashed 1px #00ccff;
}
</style>

